package com.sun.dream.fish.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.dream.fish.entity.TRoleEntity;
import com.sun.dream.fish.mapper.TRoleMapper;
import com.sun.dream.fish.mapstruct.RoleMapBasic;
import com.sun.dream.fish.service.TRoleService;
import com.sun.dream.fish.util.PageUtil;
import com.sun.dream.fish.util.ResponseUtil;
import com.sun.dream.fish.vo.PageResultVO;
import com.sun.dream.fish.vo.ResultVO;
import com.sun.dream.fish.vo.back.RoleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ljl
 * @since 2023-11-27
 */
@Service
@Slf4j
public class TRoleServiceImpl extends ServiceImpl<TRoleMapper, TRoleEntity> implements TRoleService {

    public ResultVO saveRole(RoleVO roleVO) {
        try {
            TRoleEntity tRoleEntity = RoleMapBasic.INSTANCE.voToeEntity(roleVO);
            tRoleEntity.setCreatorId(0);
            save(tRoleEntity);
        } catch (Exception e) {
            log.error("【TRoleServiceImpl】异常, ", e);
            return ResponseUtil.fail("添加角色失败");
        }
        return ResponseUtil.ok("添加角色成功");
    }

    @Override
    public PageResultVO<RoleVO> getRoleList(String name, String status, Integer pageNum, Integer pageSize) {
        Page<TRoleEntity> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNum);
        LambdaQueryWrapper<TRoleEntity> queryWrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like(TRoleEntity::getName, name);
        }
        if (StringUtils.isNotBlank(status)) {
            queryWrapper.like(TRoleEntity::getStatus, Integer.parseInt(status));
        }
        Page<TRoleEntity> newPage = page(page, queryWrapper);
        PageResultVO<RoleVO> pageResultVO = new PageResultVO<>();
        pageResultVO.setData(PageUtil.pageToVo(newPage, RoleMapBasic.class));
        return pageResultVO;
    }

    @Override
    public ResultVO updateRole(RoleVO roleVO) {
        try {
            updateById(RoleMapBasic.INSTANCE.voToeEntity(roleVO));
        } catch (Exception e) {
            log.error("【TRoleServiceImpl】异常, ", e);
            return ResponseUtil.fail("更新角色失败");
        }
        return ResponseUtil.ok("更新角色成功");
    }

    @Override
    public ResultVO deleteRole(Integer id) {
        try {
            removeById(id);
        } catch (Exception e) {
            log.error("【TRoleServiceImpl】异常, ", e);
            return ResponseUtil.fail("删除角色失败");
        }
        return ResponseUtil.ok("删除角色成功");
    }
}
